import { Component, OnInit, ViewChild, Injector } from '@angular/core';
import { BaseController } from '@shared/base-controller';
import { NzTreeNode, NzModalRef, NzModalService, NzMessageService, NzFormatEmitEvent } from 'ng-zorro-antd';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { SimpleTableComponent, SimpleTableColumn, SimpleTableButton } from '@delon/abc';
import { DictModalComponent } from './dict-modal/dict-modal.component';
import { ModalHelper } from '@delon/theme';
import { Constant } from '@core/constant';
import { DictService } from '../../../service/dict/dict.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Component({
  selector: 'app-dict-manager',
  templateUrl: './dict.component.html',
  styleUrls: ['./dict.component.less']
})
export class DictComponent extends BaseController implements OnInit {

  loading = false;
  // 分类节点集合
  nodes = [];    
  // 当前被选中的节点
  currentNode: NzTreeNode = null;
  // 表单
  dictForm: FormGroup;
  // 编辑状态
  editStatus = false;
  
  confirmModal: NzModalRef; 
  searchValue
  types = [];
  formStatus = 'update';

  addBtn = true;
  editBtn = true;
  delBtn = true;
  addElementBtn = true;
  editElementBtn = true;
  delElementBtn = true;

  ps = 10;
  q: any = {
    typeId: "-1",
    labelDefault: ""
  };
  url = this.dict.dictValues();
  data = [];
  @ViewChild('st') st: SimpleTableComponent;

  columns: SimpleTableColumn[] = [      
      { title: '编码', index: 'code' },        
      { title: '值', index: 'value'},            
      { title: '默认显示', index: 'labelDefault' },
      { title: '英文显示', index: 'labelEnUs' },
      { title: '中文显示', index: 'labelZhCh' },
      { title: '排序', index: 'orderNum' },            
      { 
          title: '操作',
          buttons: [
              { 
                  text: '编辑',
                  type: 'modal',
                  component: DictModalComponent,
                  paramName: 'dictValue',
                  params: (record: any) => { return { code: this.currentNode.origin.code} },
                  size: 600,
                  iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
                    return this.editElementBtn;
                  },
                  click: (record: any, modal: any) => this.st.reload()
              },
              {
                  text: '删除',
                  type: 'del',
                  iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
                    return this.delElementBtn;
                  },
                  click: (record: any) =>this.delElement(record.id)
              }
          ],
          fixed: 'right',
          width: '100px'
      }        
  ];

  constructor(        
      private modalService: NzModalService,
      public msg: NzMessageService, 
      private modalSrv: ModalHelper,        
      private fb: FormBuilder,
      private dict: DictService,
      public injector: Injector ,
      private cnt: Constant
  ) {
      super(injector);  
  }

  ngOnInit() {            
      // 加载字典树
      this.loadDictTypeTree();
      // 初始化表单
      this.dictForm = new FormGroup({
          id           : new FormControl({value: null, disabled: !this.editStatus}),
          code     : new FormControl({value: null, disabled: !this.editStatus}, Validators.required),
          name     : new FormControl({value: null, disabled: !this.editStatus}, Validators.required),
          parentId     : new FormControl({value: -1, disabled: !this.editStatus}, Validators.required),          
          type         : new FormControl({value: null, disabled: !this.editStatus})
      });
  }


  /** 
   * 加载分类树
   */
  loadDictTypeTree() {
      this.dict.dictTree().pipe(
          catchError(err => {                             
              return of(err);
          })
      ).subscribe(list => {            
          this.nodes = [];
          let o = this.replaceKeysDeep(list, this.mapShortToLong);            
          for (let index = 0; index < o.length; index++) {
              this.nodes.push(
                  new NzTreeNode(o[index])
              );
          }   
      })
  }

  mapShortToLong: any = {
      "id": "key",
      "label": "title"
  };

  

  /**
   * 节点单击处理事件
   * @param name 
   * @param e 
   */
  mouseAction(name: string, e: NzFormatEmitEvent): void {        
      if (name === 'click') {            
        if (e.node.isSelected) {    
          // 如果当前是编辑状态, 则选中一个节点,按钮应该确保是更新按钮
          if (this.editStatus) {
              this.formStatus = 'update';
          }                
          this.currentNode = e.node;   
          // 获取字典值列表
          this.q.typeId = e.node.key;
          this.st.load(1, this.q);
          // 获取类型详情       
          this.dict.getDictType(e.node.key).pipe(
            catchError(err => {
              return of(err);
            })
          ).subscribe(data => {            
            if (data.status === 200) {
              this.setFormValue(data.data);                
            } else {
              this.msg.error(data.message);
            }
          })
            
        } else {
            this.resetNode();  
            this.cancel();   
            this.q.labelDefault = "";
            this.q.typeId = "-1";
            this.st.load(1, this.q);           
        }
      } 
  }

  

  /**
   * 添加
   */
  add(): void {   
    if (this.formStatus == 'update' && this.editStatus) {
      this.msg.warning('有未提交的表单, 请确定是否保存');
      return;
    }     
    this.resetForm();
    this.enableForm();
    this.formStatus = 'create';
    this.editStatus = true;
    if (this.currentNode) {
      this.dictForm.get('parentId').setValue(this.currentNode.key);
    } else {
      this.dictForm.get('parentId').setValue('-1');
    }
    
  }

  doAdd() {
    for (const i in this.dictForm.controls) {
      this.dictForm.controls[ i ].markAsDirty();
      this.dictForm.controls[ i ].updateValueAndValidity();
    }        
    if (this.dictForm.get('code').dirty && this.dictForm.get('code').errors) {
        this.msg.warning('请填写编码');
        return;
    }
    if (this.dictForm.get('name').dirty && this.dictForm.get('name').errors) {
        this.msg.warning('请填写名称');
        return;
    }     
  }

  edit() {
      if (!this.currentNode) {
          this.msg.warning('请选择一个字典类型');
          return;
      }
      if (this.formStatus == 'create' && this.editStatus) {
        this.msg.warning('有未提交的表单, 请确定是否保存');
        return;
      } 
      this.editStatus = true;
      this.enableForm();
      this.formStatus = 'update';
      if (!this.dictForm.get('id').value) {
        // 获取类型详情       
        this.dict.getDictType(this.currentNode.key).pipe(
          catchError(err => {
            return of(err);
          })
        ).subscribe(data => {            
          if (data.status === 200) {
            this.setFormValue(data.data);                
          } else {
            this.msg.error(data.message);
          }
        })
      }
  }


  doEdit(): void {
      for (const i in this.dictForm.controls) {
        this.dictForm.controls[ i ].markAsDirty();
        this.dictForm.controls[ i ].updateValueAndValidity();
      }        
      if (this.dictForm.get('code').dirty && this.dictForm.get('code').errors) {
          this.msg.warning('请填写编码');
          return;
      }
      if (this.dictForm.get('name').dirty && this.dictForm.get('name').errors) {
          this.msg.warning('请填写名称');
          return;
      }      
      if (this.dictForm.valid) {
          this.loading = true;
          let v = this.dictForm.value;
          
          this.callEdit(v);
      }
  }

  callEdit(v) {
    if (this.formStatus === 'update') {
      this.dict.modifyType(v).pipe(
          catchError(err => {                             
              return of(err);
          })
      ).subscribe(data => {
          this.loading = false;
          if (data['status'] && data['status'] === 200) {                
              this.loadDictTypeTree();              
              this.msg.success('操作成功');
              this.cancel();
          } else {
              this.msg.error('操作失败' + data['message']);
          }
      })
    } else {
      this.dict.addType(v).pipe(
          catchError(err => {                             
              return of(err);
          })
      ).subscribe(data => {
          this.loading = false;
          if (data['status'] && data['status'] === 200) {                
              this.loadDictTypeTree();              
              this.msg.success('操作成功');
              this.cancel();
          } else {
              this.msg.error('操作失败' + data['message']);
          }
      })
    }
  }

  /**
   * 取消编辑
   */
  cancel() {
      this.editStatus = false;
      this.disableForm();
      if (this.formStatus === 'create') {
        this.resetForm();
      }
  }

  del() {
      if (this.currentNode) {
          this.confirmModal = this.modalService.confirm({
              nzTitle: `删除提醒`,
              nzContent: `你确定删除字典类型 ${this.currentNode.title} ?`,
              nzOnOk: () => {
                  this.doDel();
              }
          });
          
      } else {
          this.msg.warning('请选择要删除的字典类型');
      } 
  }

  doDel() {
      this.dict.deleteType(this.currentNode.key).pipe(
          catchError(err => {                             
              return of(err);
          })
      ).subscribe(ret => {
          if (ret.status === 200) {
              this.resetNode();
              this.loadDictTypeTree();     
          } else {
              this.msg.error(ret.message);
          }
      });
  }

  resetNode() {
    this.currentNode = null;    
    this.resetForm();
  }

  resetForm() {
    for (const i in this.dictForm.controls) {
      this.dictForm.controls[ i ].reset();  
    }
    this.dictForm.get('parentId').setValue("-1");    
  }

  setFormValue(node) {
    this.resetForm();
    this.dictForm.patchValue(node);
  }  

  enableForm() {
    for (const i in this.dictForm.controls) {
      this.dictForm.controls[ i ].enable();  
    }
  }

  disableForm() {    
    for (const i in this.dictForm.controls) {
      this.dictForm.controls[ i ].disable();  
    }
  }

  delElement(id: string) {
    this.dict.deleteDictValue(id).pipe(
        catchError(err => {                             
            return of(err);
        })
    ).subscribe(ret=>{
        if (ret.status === 200) {
            this.st.load(1, this.q);         
        } else {
            this.msg.error(ret.message);
        }
    });
  }
  addElement() {
    if (this.currentNode) {
        this.modalSrv.static(DictModalComponent, { typeId: this.currentNode.key, code: this.currentNode.origin.code }, 600).subscribe((e) => {
            this.st.load(1, this.q);            
        });
    } else {
        this.msg.warning('请先选择一个字典类型');
    }
  }

}
